import BaseAds from "./BaseAds";
import { EventTool } from "../Tool/EventTool";
import TimeTool from "../Tool/TimeTool";
import MsgDispatcher, { MsgType } from "../Tool/MsgDispatcher";
import UIManager from "../UI/UIManager";
import WaitingView from "../../View/WaittingView";
import { TipView } from "../../View/TipView";
import KongFuLoader from "../../MyLoader/KongFuResourLoader";


enum BannerState {
    Show = "Show",
    Hide = "Hide",
    None = "None"
}




export class QQAds extends BaseAds {

    //=======================QQAdInfos=====================
    //bannner
    private s_NormalBannerId = "cc856292b43af6cd90265f54678e6efe";
    //rewardVideo
    private s_RewardVideoId = "b68a46a786ca6236092bd0cff084916c";
    //InterstitialAd
    private s_InterstitialId = "90357187227a7e8650822c1064ce364d";
    //==================AppBoxAd==============
    private s_AppBoxId = "fce3015757fb6b5de742269f4e58e4d9";
    private s_AppBoxAd: any = null;
    //========BlockAd==============
    private s_BlockAds:{[key:string]:any}={};

    private m_bannerState = BannerState.None;
    private s_Banner: BannerAd = null;
    //=====InsterstitialAd====
    private s_interstitialLoaded = false;
    private s_InterstitialAd: InterstitialAd = null;

    //video
    private s_RewardVideoAd: RewardedVideoAd = null;
    private s_rewardVideoLoaded = false;

    private s_safeHeight = 0;


    ///是否有激励视频广告
    public get HasRewardVideo()  {
        console.log("HasRewardVideo");

        if (this.s_RewardVideoAd == null) {
            this.Created30RewardedVideoAd();
            return false;
        }
        //未加载
        if (!this.s_rewardVideoLoaded) {
            this.s_RewardVideoAd.load();
        }
        return this.s_rewardVideoLoaded;
    }

    /**是否有激励视频广告*/
    public get HasInterstiatialAd()  {
        if (this.s_InterstitialAd == null) {
            this.CreatedInterstitialAd();
            return false;
        }
        //未加载
        if (!this.s_interstitialLoaded && this.CanShowInterstitialAd()) {
            this.s_InterstitialAd.load();
        }
        return this.s_interstitialLoaded;
    }

    public get SyncSystemInfo()  {
        if (this.s_syncsystemInfoS == null) {
            this.s_syncsystemInfoS = this.m_platform.getSystemInfoSync();
            this.SDKVersion = this.s_syncsystemInfoS.SDKVersion;
            console.log("model=" + this.s_syncsystemInfoS.model);
            console.log("pixelRatio=" + this.s_syncsystemInfoS.pixelRatio);
            console.log("windowWidth=" + this.s_syncsystemInfoS.windowWidth);
            console.log("windowHeight=" + this.s_syncsystemInfoS.windowHeight);
            console.log("ScreenWidth=" + this.s_syncsystemInfoS.screenWidth);
            console.log("screenHeight=" + this.s_syncsystemInfoS.screenHeight);
            console.log(this.s_syncsystemInfoS.language);
            console.log(this.s_syncsystemInfoS.version);
            console.log(this.s_syncsystemInfoS.SDKVersion);
            console.log(this.s_syncsystemInfoS.platform);
        }

        return this.s_syncsystemInfoS;
    }
    //SDK版本
    private SDKVersion = "0.0.0";


    private s_framecount = 3;
    public InitAd(ishowbannerfc: Function = null, ishowintersitialfc: Function = null)  {
        Laya.timer.frameLoop(this.s_framecount, this, this.AdFrameInvoke)
        this.CreateBanner();
        this.CreatedInterstitialAd();
        this.CreatedcreateAppBox();
        this.HasRewardVideo;
        this.s_IsShowBannermetd = ishowbannerfc;
        MsgDispatcher.Register(MsgType.GameLoadOver, "WeChatAd", this.OnGameLoadOver.bind(this));
    }

    OnGameLoadOver(){
        this.CreatedBlockAd();
    }


    //显示广告
    public ShowBannerAd()  {
        if (this.s_Banner != null) {
            EventTool.LogEvent("banner成功展示");
        }
        this.m_bannerState = BannerState.Show;
    }

    //隐藏Banner广告
    public HideBannerAd()  {
        this.m_bannerState = BannerState.Hide;
        this.CreateBanner();
    }

    /**显示插屏广告 */
    public ShowInterstitialAd()  {
        if (this.s_IsShowIntersitialmetd != null && !this.s_IsShowIntersitialmetd()) {
            return;
        }
        if (this.HasInterstiatialAd) {
            this.s_InterstitialAd.show();
        }
    }


        /**显示积木广告 */
    public ShowBlockAd(blockType:string){
          this.s_BlockAds[blockType]&&this.s_BlockAds[blockType].show();
    }
    /**隐藏积木广告 */
    public HideBlockAd(blockType:string){
        this.s_BlockAds[blockType]&&this.s_BlockAds[blockType].hide();
  }

    //显示激励视频广告
    public ShowRewardVieoAd(callback: Function)  {
        UIManager.Instance.ShowInterView(WaitingView.name);
        this.s_videoCallBack = callback;
        console.log("ShowRewardAd " + (this.s_videoCallBack == null));
        if (this.HasRewardVideo) {
            this.s_RewardVideoAd.show().
                then(() =>  {
                    this.s_rewardVideoLoaded = false
                }
                ).
                catch((e) =>  {
                    console.error(e.message);
                    this.s_videoCallBack(false);
                    UIManager.Instance.ShowInterView(TipView.name, "奖励正在准备中，请稍后再试");
                    UIManager.Instance.HideInterView(WaitingView.name);
                });
        }
        else {
            this.s_videoCallBack(false);
            UIManager.Instance.ShowInterView(TipView.name, "奖励正在准备中，请稍后再试");
            UIManager.Instance.HideInterView(WaitingView.name);
        }
    }

    public ShowAppBoxAd()  
    {
        this.s_AppBoxAd&&this.s_AppBoxAd.show();

    }

    public HideAppBoxAd()  
    {
        this.s_AppBoxAd&&this.s_AppBoxAd.hide();
    }

    private CanShowBannerAd()  {
        if (this.SDKVersion == "0.0.0")
            this.SyncSystemInfo;
        return true;
    }

    private CanShowRewardVideoAd()  {
        if (this.SDKVersion == "0.0.0")
            this.SyncSystemInfo;
        return true;
    }

    private CanShowInterstitialAd(){
        if (this.SDKVersion == "0.0.0")
            this.SyncSystemInfo;
        return this.compareVersion(this.SDKVersion, '1.12.0') >= 0;;
    }

    private CanShowAppBoxAd()  {
        if (this.SDKVersion == "0.0.0")
            this.SyncSystemInfo;
        return this.compareVersion(this.SDKVersion, '1.7.1') >= 0;;
    }

    private CanShowBlockBoxAd()  {
        if (this.SDKVersion == "0.0.0")
            this.SyncSystemInfo;
        return this.compareVersion(this.SDKVersion, '1.15.0') >= 0;;
    }



    /////////=========================Banner=============================
    private CreateBanner()  {
        if (this.SyncSystemInfo == null)
            return;

        let bannerAd = this.m_platform.createBannerAd({
            adUnitId: this.s_NormalBannerId,
            style: {
                width: 300,
                left: (this.SyncSystemInfo.screenWidth - 300) / 2 + 0.1,
                top: this.SyncSystemInfo.screenHeight - 105,
                adIntervals: 30
            }
        })

        if (this.s_Banner != null)
            this.s_Banner.destroy()

        this.s_Banner = null;
        bannerAd.onLoad(() => {
            if (this.s_Banner != null)
                this.s_Banner.destroy()
            this.s_Banner = bannerAd;
            console.log('banner 广告加载成功')
        })

        bannerAd.onResize(size =>  {
            console.log("bannerSize=" + size.width + " height=" + size.height + " realwidth=" + bannerAd.style.realWidth + " realheight=" + bannerAd.style.realHeight);
            bannerAd.style.left = (this.SyncSystemInfo.screenWidth - size.width) / 2 + 0.1;
            bannerAd.style.top = this.SyncSystemInfo.screenHeight - size.height;
        }
        );

        bannerAd.onError(err => {
            console.error("BannerIdError" + err);
            EventTool.LogEvent("banner加载失败 " + err);
        })
    }


    ////////////RewardVidoe=============================
    private Created30RewardedVideoAd()  {
        if (!this.CanShowRewardVideoAd()) {
            return;
        }
        this.s_RewardVideoAd = this.m_platform.createRewardedVideoAd({ adUnitId: this.s_RewardVideoId })
        this.s_RewardVideoAd.onLoad(() => {
            this.s_rewardVideoLoaded = true;
            EventTool.LogEvent("激励视频30秒加载成功");
            console.log('激励视频 广告加载成功')
        })
        this.s_RewardVideoAd.onError(err => {
            this.s_rewardVideoLoaded = false;
            EventTool.LogEvent("激励视频30秒加载失败 " + err);
            console.log("30激励加载失败:" + err)
        })

        this.s_RewardVideoAd.onClose(function (res)  {
            EventTool.LogEvent("激励视频退出观看");
            if (this.s_videoCallBack != null) {
                console.log("Has CallBack");
                if (res && res.isEnded || res == undefined) {
                    console.log("WatchOver");
                    // 正常播放结束，可以下发游戏奖励
                    this.s_videoCallBack(true);
                }
                else  {
                    console.log("OntWatchOver");
                    this.s_videoCallBack(false);
                }
                this.s_videoCallBack = null;
            }
            UIManager.Instance.HideInterView(WaitingView.name);

        }.bind(this));
    }


    //===========================InterstitialAd==================
    private CreatedInterstitialAd() {
        if (!this.CanShowInterstitialAd()) {
            return;
        }
        this.s_InterstitialAd = this.m_platform.createInterstitialAd({ adUnitId: this.s_InterstitialId })
        this.s_InterstitialAd.onLoad(() => {
            this.s_interstitialLoaded = true;
            console.log('插屏 广告加载成功')
        })
        this.s_InterstitialAd.onError(err => {
            this.s_interstitialLoaded = false;
            console.log("插屏广告加载失败:" + err)
        })

        this.s_InterstitialAd.onClose(e => {
            if (this.s_interstitialAdCallBack != null) {
                this.s_interstitialAdCallBack();
            }
            this.s_interstitialAdCallBack = null;
        })
    }


    //===========================AppBox==================
    private CreatedcreateAppBox() {
        if (!this.CanShowAppBoxAd()) {
            return;
        }
        this.s_AppBoxAd = this.m_platform.createAppBox({adUnitId: this.s_AppBoxId });
        this.s_AppBoxAd&&this.s_AppBoxAd.load();
    }


    //===========================AppBox==================
    private CreatedBlockAd()
    {
        if (!this.CanShowBlockBoxAd()) {
            return;
        }
        let blockConfig=KongFuLoader.Instance.GetBlockAdConfigData;
        for (let index = 0; index < blockConfig.length; index++) {
            const element = blockConfig[index];
            let blockid=element.BlockId;
            let leftbor=element.Left;
            let topbor=element.Top;
            if (element.Left<0) 
            { leftbor=this.SyncSystemInfo.screenWidth+element.Left;}
            if (element.Top<0) 
            { leftbor=this.SyncSystemInfo.height+element.Top;}
            console.log("BlockId=" +element.BlockId+" left="+leftbor+" top="+topbor);
                let appbox = this.m_platform.createBlockAd({
                adUnitId: element.BlockId,  
                style: {
                    left: leftbor,
                    top: topbor,
                },
                size:element.Size,
                orientation:element.Orientation,
            })
            this.s_BlockAds[element.BlockType]=appbox;
            this.s_BlockAds[element.BlockType].onLoad(() => {
                console.log(element.BlockType + ' BlockAd 广告加载成功')
            })

            this.s_BlockAds[element.BlockType].onResize(size =>  {
                console.log("BlockAdSize=" + size.width + " height=" + size.height);
            }
            );

            this.s_BlockAds[element.BlockType].onError(err => {
                console.error("BlockAdError" + JSON.stringify(err) );
            })
        }

    }


    //版本号比较
    public compareVersion(v1, v2) {
        v1 = v1.split('.')
        v2 = v2.split('.')
        const len = Math.max(v1.length, v2.length)

        while (v1.length < len) {
            v1.push('0')
        }
        while (v2.length < len) {
            v2.push('0')
        }

        for (let i = 0; i < len; i++) {
            const num1 = parseInt(v1[i])
            const num2 = parseInt(v2[i])

            if (num1 > num2) {
                return 1
            } else if (num1 < num2) {
                return -1
            }
        }

        return 0
    }

    private BannerReFlash()  {
        if (this.s_IsShowBannermetd != null && !this.s_IsShowBannermetd())
            return;

        if (!this.CanShowBannerAd())
            return;

        if (this.SyncSystemInfo == null) {
            console.log("未获取到系统信息 广告显示失败");
            return;
        }


        switch (this.m_bannerState) {
            case BannerState.Show:
                if (this.s_Banner != null) {
                    this.s_Banner.show();
                    this.m_bannerState = BannerState.None
                }
                break;
            case BannerState.Hide:
                if (this.s_Banner != null) {
                    this.s_Banner.hide();
                    this.m_bannerState = BannerState.None
                }
                break;
            case BannerState.None:

                break;
            default:
                console.warn("QQAds Not Found State " + this.m_bannerState);
                break;
        }

    }

    //
    public static NativeToProgram(gameId: string, game: string)  {

    }


    private AdFrameInvoke()  {
        this.BannerReFlash();
    }


    //0 为top 1为height 
    public GetMenueBtnTop(): Array<number>  {
        let meunesizeInfo = [0, 0];
            let menue = this.m_platform.getMenuButtonBoundingClientRect();
            if (menue==null) {
                console.log("获取菜单按钮信息失败 ");
            }
            else{
                meunesizeInfo[0] = menue.top;
                meunesizeInfo[1] = menue.height;
            }
  

        return meunesizeInfo;
    }


    OnAudioInterruptionEnd(callBack: Function)  {
        this.m_platform.onAudioInterruptionEnd(callBack);
    }
}